package utils;

import ui.InterceptFilterPanel;
import ui.PermissionTestPanel;
import ui.RulePanel;

import javax.swing.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class ConfigUtil {
    
    /**
     * 保存配置到文件
     * @param parent 父组件，用于显示对话框
     * @param permissionTestPanel PermissionTestPanel实例
     * @param fileTypeComboBox 文件类型下拉框
     * @param exportFilterComboBox 导出过滤下拉框
     * @param removeDuplicatesCheckBox 去除重复项复选框
     */
    public static void saveConfiguration(JComponent parent, 
                                        PermissionTestPanel permissionTestPanel,
                                        JComboBox<String> fileTypeComboBox,
                                        JComboBox<String> exportFilterComboBox,
                                        JCheckBox removeDuplicatesCheckBox) {
        if (permissionTestPanel == null) {
            JOptionPane.showMessageDialog(parent, "无法获取配置数据", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("保存配置文件");
        fileChooser.setSelectedFile(new File("PermissionTest_Config.json"));
        
        int userSelection = fileChooser.showSaveDialog(parent);
        
        if (userSelection == JFileChooser.APPROVE_OPTION) {
            File fileToSave = fileChooser.getSelectedFile();
            String filePath = fileToSave.getAbsolutePath();
            
            // 确保文件有.json扩展名
            if (!filePath.endsWith(".json")) {
                filePath += ".json";
                fileToSave = new File(filePath);
            }
            
            try {
                // 创建配置对象
                Map<String, Object> config = new HashMap<>();
                
                // 保存配置中心的设置
                Map<String, Object> configCenter = new HashMap<>();
                
                // 临时请求头：Base64编码
                String tempHeaders = permissionTestPanel.getConfigPanel().getTempHeaders();
                String encodedHeaders = Base64.getEncoder().encodeToString(tempHeaders.getBytes());
                configCenter.put("tempHeaders", encodedHeaders);
                
                // 复选框状态：JSON格式
                Map<String, Boolean> checkBoxes = new HashMap<>();
                checkBoxes.put("checkUnauthorized", permissionTestPanel.getConfigPanel().isUnauthorizedCheckSelected());
                checkBoxes.put("ignore204304", permissionTestPanel.getConfigPanel().isIgnore204304Checked());
                checkBoxes.put("avoid304", permissionTestPanel.getConfigPanel().isAvoid304Checked());
                checkBoxes.put("useConfigRules", permissionTestPanel.getConfigPanel().isUseConfigRulesChecked());
                configCenter.put("checkBoxes", checkBoxes);
                
                // 低权限规则面板设置
                Map<String, Object> lowPrivilegeRules = new HashMap<>();
                lowPrivilegeRules.put("logicRelation", permissionTestPanel.getConfigPanel().getLowPrivilegeRulePanel().getLogicRelation());
                
                // 低权限规则内容Base64编码
                StringBuilder lowPrivilegeRulesContent = new StringBuilder();
                for (RulePanel.Rule rule : permissionTestPanel.getConfigPanel().getLowPrivilegeRulePanel().getRules()) {
                    lowPrivilegeRulesContent.append(rule.getType()).append("|").append(rule.getContent()).append("\n");
                }
                String encodedLowPrivilegeRules = Base64.getEncoder().encodeToString(lowPrivilegeRulesContent.toString().getBytes());
                lowPrivilegeRules.put("rules", encodedLowPrivilegeRules);
                configCenter.put("lowPrivilegeRules", lowPrivilegeRules);
                
                // 未授权规则面板设置
                Map<String, Object> unauthorizedRules = new HashMap<>();
                unauthorizedRules.put("logicRelation", permissionTestPanel.getConfigPanel().getUnauthorizedRulePanel().getLogicRelation());
                
                // 未授权规则内容Base64编码
                StringBuilder unauthorizedRulesContent = new StringBuilder();
                for (RulePanel.Rule rule : permissionTestPanel.getConfigPanel().getUnauthorizedRulePanel().getRules()) {
                    unauthorizedRulesContent.append(rule.getType()).append("|").append(rule.getContent()).append("\n");
                }
                String encodedUnauthorizedRules = Base64.getEncoder().encodeToString(unauthorizedRulesContent.toString().getBytes());
                unauthorizedRules.put("rules", encodedUnauthorizedRules);
                configCenter.put("unauthorizedRules", unauthorizedRules);
                
                // 拦截过滤器规则面板设置
                Map<String, Object> interceptFilterRules = new HashMap<>();
                
                // 拦截过滤器规则内容Base64编码
                StringBuilder interceptFilterRulesContent = new StringBuilder();
                for (InterceptFilterPanel.Rule rule : permissionTestPanel.getConfigPanel().getInterceptFilterRulePanel().getRules()) {
                    interceptFilterRulesContent.append(rule.getType()).append("|").append(rule.getContent()).append("\n");
                }
                String encodedInterceptFilterRules = Base64.getEncoder().encodeToString(interceptFilterRulesContent.toString().getBytes());
                interceptFilterRules.put("rules", encodedInterceptFilterRules);
                configCenter.put("interceptFilterRules", interceptFilterRules);
                
                config.put("configCenter", configCenter);
                
                // 保存/恢复设置
                Map<String, Object> saveRestore = new HashMap<>();
                saveRestore.put("fileType", fileTypeComboBox.getSelectedItem());
                saveRestore.put("exportFilter", exportFilterComboBox.getSelectedItem());
                saveRestore.put("removeDuplicates", removeDuplicatesCheckBox.isSelected());
                config.put("saveRestore", saveRestore);
                
                // 使用Gson将配置写入文件
                Gson gson = new GsonBuilder().setPrettyPrinting().create();
                try (FileOutputStream fos = new FileOutputStream(fileToSave)) {
                    fos.write(gson.toJson(config).getBytes());
                }
                
                JOptionPane.showMessageDialog(parent, "配置已成功保存到: " + filePath, "成功", JOptionPane.INFORMATION_MESSAGE);
            } catch (IOException e) {
                JOptionPane.showMessageDialog(parent, "保存配置失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                LoggerUtil.logOutput("保存配置失败: " + e.getMessage());
            }
        }
    }
    
    /**
     * 从文件恢复配置
     * @param parent 父组件，用于显示对话框
     * @param permissionTestPanel PermissionTestPanel实例
     * @param fileTypeComboBox 文件类型下拉框
     * @param exportFilterComboBox 导出过滤下拉框
     * @param removeDuplicatesCheckBox 去除重复项复选框
     */
    public static void restoreConfiguration(JComponent parent,
                                           PermissionTestPanel permissionTestPanel,
                                           JComboBox<String> fileTypeComboBox,
                                           JComboBox<String> exportFilterComboBox,
                                           JCheckBox removeDuplicatesCheckBox) {
        if (permissionTestPanel == null) {
            JOptionPane.showMessageDialog(parent, "无法获取配置数据", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("选择配置文件");
        
        int userSelection = fileChooser.showOpenDialog(parent);
        
        if (userSelection == JFileChooser.APPROVE_OPTION) {
            File fileToOpen = fileChooser.getSelectedFile();
            
            try {
                // 使用Gson读取配置文件
                Gson gson = new Gson();
                Map<String, Object> config;
                try (FileReader reader = new FileReader(fileToOpen)) {
                    config = gson.fromJson(reader, new TypeToken<Map<String, Object>>(){}.getType());
                }
                
                if (config == null) {
                    JOptionPane.showMessageDialog(parent, "配置文件格式错误", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                
                // 恢复配置中心的设置
                Object configCenterObj = config.get("configCenter");
                if (configCenterObj instanceof Map) {
                    Map<String, Object> configCenter = convertMap(configCenterObj);
                    
                    // 恢复临时请求头
                    Object encodedHeadersObj = configCenter.get("tempHeaders");
                    if (encodedHeadersObj instanceof String encodedHeaders) {
                        byte[] decodedBytes = Base64.getDecoder().decode(encodedHeaders);
                        String tempHeaders = new String(decodedBytes);
                        permissionTestPanel.getConfigPanel().setTempHeaderContent(tempHeaders);
                    }
                    
                    // 恢复复选框状态
                    Object checkBoxesObj = configCenter.get("checkBoxes");
                    if (checkBoxesObj instanceof Map) {
                        Map<String, Object> checkBoxes = convertMap(checkBoxesObj);
                        
                        Object checkUnauthorizedObj = checkBoxes.get("checkUnauthorized");
                        if (checkUnauthorizedObj instanceof Boolean) {
                            permissionTestPanel.getConfigPanel().setUnauthorizedCheck((Boolean) checkUnauthorizedObj);
                        }
                        
                        Object ignore204304Obj = checkBoxes.get("ignore204304");
                        if (ignore204304Obj instanceof Boolean) {
                            permissionTestPanel.getConfigPanel().setIgnore204304Check((Boolean) ignore204304Obj);
                        }
                        
                        Object avoid304Obj = checkBoxes.get("avoid304");
                        if (avoid304Obj instanceof Boolean) {
                            permissionTestPanel.getConfigPanel().setAvoid304Check((Boolean) avoid304Obj);
                        }
                        
                        Object useConfigRulesObj = checkBoxes.get("useConfigRules");
                        if (useConfigRulesObj instanceof Boolean) {
                            permissionTestPanel.getConfigPanel().setUseConfigRulesCheck((Boolean) useConfigRulesObj);
                        }
                    }
                    
                    // 恢复低权限规则
                    Object lowPrivilegeRulesObj = configCenter.get("lowPrivilegeRules");
                    if (lowPrivilegeRulesObj instanceof Map) {
                        Map<String, Object> lowPrivilegeRules = convertMap(lowPrivilegeRulesObj);
                        
                        Object logicRelationObj = lowPrivilegeRules.get("logicRelation");
                        if (logicRelationObj instanceof String) {
                            permissionTestPanel.getConfigPanel().getLowPrivilegeRulePanel().setLogicRelation((String) logicRelationObj);
                        }
                        
                        Object encodedRulesObj = lowPrivilegeRules.get("rules");
                        if (encodedRulesObj instanceof String encodedRules) {
                            byte[] decodedBytes = Base64.getDecoder().decode(encodedRules);
                            String rulesContent = new String(decodedBytes);
                            permissionTestPanel.getConfigPanel().getLowPrivilegeRulePanel().loadRules(rulesContent);
                        }
                    }
                    
                    // 恢复未授权规则
                    Object unauthorizedRulesObj = configCenter.get("unauthorizedRules");
                    if (unauthorizedRulesObj instanceof Map) {
                        Map<String, Object> unauthorizedRules = convertMap(unauthorizedRulesObj);
                        
                        Object logicRelationObj = unauthorizedRules.get("logicRelation");
                        if (logicRelationObj instanceof String) {
                            permissionTestPanel.getConfigPanel().getUnauthorizedRulePanel().setLogicRelation((String) logicRelationObj);
                        }
                        
                        Object encodedRulesObj = unauthorizedRules.get("rules");
                        if (encodedRulesObj instanceof String encodedRules) {
                            byte[] decodedBytes = Base64.getDecoder().decode(encodedRules);
                            String rulesContent = new String(decodedBytes);
                            permissionTestPanel.getConfigPanel().getUnauthorizedRulePanel().loadRules(rulesContent);
                        }
                    }
                    
                    // 恢复拦截过滤器规则
                    Object interceptFilterRulesObj = configCenter.get("interceptFilterRules");
                    if (interceptFilterRulesObj instanceof Map) {
                        Map<String, Object> interceptFilterRules = convertMap(interceptFilterRulesObj);
                        
                        Object encodedRulesObj = interceptFilterRules.get("rules");
                        if (encodedRulesObj instanceof String encodedRules) {
                            byte[] decodedBytes = Base64.getDecoder().decode(encodedRules);
                            String rulesContent = new String(decodedBytes);
                            // 使用专门用于配置恢复的方法，完全替换规则包括默认规则
                            permissionTestPanel.getConfigPanel().getInterceptFilterRulePanel().loadRulesForConfigRestore(rulesContent);
                        }
                    }
                }
                
                // 恢复保存/恢复设置
                Object saveRestoreObj = config.get("saveRestore");
                if (saveRestoreObj instanceof Map) {
                    Map<String, Object> saveRestore = convertMap(saveRestoreObj);
                    
                    Object fileTypeObj = saveRestore.get("fileType");
                    if (fileTypeObj != null) {
                        fileTypeComboBox.setSelectedItem(fileTypeObj.toString());
                    }
                    
                    Object exportFilterObj = saveRestore.get("exportFilter");
                    if (exportFilterObj != null) {
                        exportFilterComboBox.setSelectedItem(exportFilterObj.toString());
                    }
                    
                    Object removeDuplicatesObj = saveRestore.get("removeDuplicates");
                    if (removeDuplicatesObj instanceof Boolean) {
                        removeDuplicatesCheckBox.setSelected((Boolean) removeDuplicatesObj);
                    }
                }
                
                JOptionPane.showMessageDialog(parent, "配置已成功恢复", "成功", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(parent, "恢复配置失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                LoggerUtil.logError("恢复配置失败: " + e.getMessage());
            }
        }
    }
    
    /**
     * 将Object转换为Map<String, Object>
     * @param obj 要转换的对象
     * @return 转换后的Map
     */
    private static Map<String, Object> convertMap(Object obj) {
        if (obj instanceof Map) {
            // 使用Gson将对象重新序列化和反序列化
            Gson gson = new Gson();
            String json = gson.toJson(obj);
            return gson.fromJson(json, new TypeToken<Map<String, Object>>(){}.getType());
        }
        return new HashMap<>();
    }
}
